#include "execute_statement.h"
#include "show_info.h"

ExecuteResult excute_statement(Statement *statement, Table *table)
{
    switch (statement->state_type)
    {
    case STATEMENT_SELECT:
        return execute_select(statement, table);
    case STATEMENT_INSERT:
        return execute_insert(statement, table);
    default:
        break;
    }
}

ExecuteResult execute_insert(Statement *statement, Table *table)
{
    Cursor *cursor = table_find(table, statement->row_to_insert.id);
    if (cursor_value(cursor)->key == statement->row_to_insert.id)
    {
        return EXECUTE_DUPLICATE_KEY;
    }

    leaf_node_insert(cursor, statement->row_to_insert.id, &statement->row_to_insert);
    return EXECUTE_SUCCESS;
};

ExecuteResult execute_select(Statement *statement, Table *table)
{
    Row row;
    Cursor *cursor = table_start(table);
    while (!cursor->end_of_table)
    {
        deserialize_row(&cursor_value(cursor)->value, &row);
        cursor_advance(cursor);
        print_row(&row);
    }
    return EXECUTE_SUCCESS;
};